import json

from django import forms
from rest_framework.views import APIView
from app01.models import Device, Deviceinfo
from app01.Baseview import MsgView, BasedAPIView
from django.http import JsonResponse
from rest_framework import serializers


class DeviceinfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Deviceinfo
        fields = '__all__'

class DeviceSerializer(serializers.ModelSerializer):
    dev_info = DeviceinfoSerializer(required=False)

    class Meta:
        model = Device
        fields = ['id', 'dev_type', 'name', 'sort', 'address', 'number', 'status', 'remarks', 'dev_info']

    def create(self, validated_data):
        dev_info_data = validated_data.pop('dev_info', None)
        device = Device.objects.create(**validated_data)
        if dev_info_data:
            device_info = Deviceinfo.objects.create(**dev_info_data)
            device.dev_info = device_info
            device.save()
        return device

    def update(self, instance, validated_data):
        # 更新Device实例，并可选地更新Deviceinfo
        dev_info_data = validated_data.pop('dev_info', None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        if dev_info_data:
            if instance.dev_info:
                for attr, value in dev_info_data.items():
                    setattr(instance.dev_info, attr, value)
                instance.dev_info.save()
            else:
                instance.dev_info = Deviceinfo.objects.create(**dev_info_data)
                instance.save()

        return instance


class DeviceForm(forms.ModelForm):
    class Meta:
        model = Device
        fields = ['dev_type', 'name', 'address', 'number', 'status', 'remarks']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 检查表单数据中的字段名是否都是模型中的字段
        if self.is_bound:  # 只有当表单绑定了数据时，才进行检查
            model_fields = {f.name for f in Device._meta.get_fields()}
            form_fields = set(self.data.keys())
            extra_fields = form_fields - model_fields
            if extra_fields:
                errors = "检查参数是否正确:"
                self.add_error(None, errors)


class Device_Api(BasedAPIView):
    def get_page_all(self, request):
        try:
            page=int(request.GET.get["page"])
            pagesize =int(request.GET.get["pagesize"])
        except Exception as e:
            page = 1
            pagesize = 10
        if page < 1 :
            page = 1
        start_page = (page - 1) * pagesize
        end_page = page * pagesize

        name = request.GET.get('name')
        dev_type = request.GET.get('dev_type')
        dic = {}
        if name:
            dic["name__icontains"] = name
        if dev_type:
            dic["dev_type__icontains"] = dev_type

        datas = Device.objects.filter(**dic).order_by('-id')[start_page:end_page]
        data = []
        for item in datas:
            try:
                dev_info = Deviceinfo.objects.get(id=item.dev_info_id)
            except Deviceinfo.DoesNotExist:
                dev_info = None
            device_data = {
                "id": item.id,
                "CreatedTime": item.CreatedTime.strftime("%Y-%m-%d %H:%M:%S") if item.CreatedTime else None,
                "UpdatedTime": item.UpdatedTime.strftime("%Y-%m-%d %H:%M:%S") if item.UpdatedTime else None,
                "dev_type": item.dev_type,
                "name": item.name,
                "address": item.address,
                "number": item.number,
                "status": item.status,
                "remarks": item.remarks,
                "dev_info": {
                    "username": dev_info.username,
                    "password": dev_info.password,
                    "name": dev_info.name,
                    "remarks": dev_info.remarks,
                } if dev_info is not None else None,
            }
            data.append(device_data)
        return super().success(data=data)

    # def get_by_id(self, request):
    #     uid = request.GET.get('id')
    #     datas = Device.objects.filter(id=uid)
    #     data = []
    #     for item in datas:
    #         data_dic = {
    #             "id": item.id,
    #             "CreatedTime": item.CreatedTime.strftime("%Y-%m-%d %H:%M:%S") if item.CreatedTime else None,
    #             "UpdatedTime": item.UpdatedTime.strftime("%Y-%m-%d %H:%M:%S") if item.UpdatedTime else None,
    #             "dev_type": item.dev_type,
    #             "name": item.name,
    #             "address": item.address,
    #             "number": item.number,
    #             "status": item.status,
    #             "remarks": item.remarks,
    #             "dev_info": {
    #                 "username": item.dev_info.username,
    #                 "password": item.dev_info.password,
    #             }
    #         }
    #         data.append(data_dic)
    #     return super().success(data)

    def add_info(self, request):
        data = json.loads(request.body)
        try:
            dev_info_id = data.get('dev_info_id')
            dev_info = Deviceinfo.objects.get(pk=dev_info_id) if dev_info_id else None

            new_device = Device(
                dev_type=data.get('dev_type'),
                name=data.get('name'),
                sort=data.get('sort', 1),
                address=data.get('address'),
                number=data.get('number', 1),
                status=data.get('status', 1),
                remarks=data.get('remarks'),
                dev_info=dev_info,
            )
            new_device.save()

            response_data = {
                'id': new_device.id,
                'name': new_device.name,
            }
            return JsonResponse(response_data, status=201)

        except Deviceinfo.DoesNotExist:
            return JsonResponse({'message': 'Deviceinfo not found'}, status=404)

        except Exception as e:
            return JsonResponse({'message': str(e)}, status=500)
        ###----------serializer----------
        # serializer = DeviceSerializer(data=request.data)
        # if serializer.is_valid():
        #     serializer.save()
        #     return super().success(data=serializer.data)
        # return super().error(msg=serializer.errors)
        ###----------modelForm----------
        # form = DeviceForm(json.loads(request.body))
        # if form.is_valid():
        #     data = form.data
        #     form.save()
        #     return super().success(msg="新增成功", data=data)
        # else:
        #     return super().error(msg=form.errors)

    def edit_info(self, request):
        data = json.loads(request.body)
        uid = data.get('id')
        dev_info_id = data.get('dev_info_id')
        if not uid:
            return JsonResponse({'message': 'ID is required'})
        instance = Device.objects.get(pk=uid)
        update_fields = ['name', 'address', 'number', 'status', 'remarks']
        for field in update_fields:
            if field in data:
                setattr(instance, field, data[field])
        if dev_info_id is not None:
            dev_info = Deviceinfo.objects.get(pk=dev_info_id)
            instance.dev_info = dev_info
            dev_info_name = dev_info.name
        instance.save(update_fields=update_fields + ['dev_info'])
        response_data = {
            "id": instance.id,
            "address": instance.address,
            "name": instance.name,
            "number": instance.number,
            "status": instance.status,
            "remarks": instance.remarks,
            'dev_info_name': dev_info_name if 'dev_info_id' in data else None
        }
        return super().success(msg="修改成功", data=response_data)

    def del_info(self, request):
        uid = request.GET.get('id', "")
        try:
            DeviceForm.objects.get(pk=uid).delete()
            return super().success(msg="删除成功")
        except DeviceForm.DoesNotExist:
            return super().error(msg="ID不存在")

